<!DOCTYPE html>
<html>
<head>
    <title>流式对话演示</title>
    <meta charset="UTF-8">
    <style>
        /* 基础样式 */
        body {
            margin: 0;
            padding: 20px;
            background: #f0f2f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            height: 90vh;
            display: flex;
            flex-direction: column;
        }
        
        /* 消息容器 */
        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        /* 消息气泡 */
        .message {
            margin: 10px 0;
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
        }
        
        .user-message {
            background: #1890ff;
            color: white;
            margin-left: auto;
        }
        
        .bot-message {
            background: #f5f5f5;
            margin-right: auto;
        }
        
        /* 输入区域 */
        .input-area {
            display: flex;
            gap: 10px;
        }
        
        #input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        
        button {
            padding: 12px 24px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="messages" id="messages"></div>
        <div class="input-area">
            <input type="text" id="input" placeholder="输入消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        let isGenerating = false;

        async function sendMessage() {
            if (isGenerating) return;

            const input = document.getElementById('input');
            const userMessage = input.value.trim();
            if (!userMessage) return;

            // 禁用输入
            input.value = '';
            isGenerating = true;

            // 添加用户消息
            addMessage(userMessage, 'user');

            try {
                // 创建AI消息占位符
                const botMessageElement = addMessage('', 'bot');

                // 发起流式请求
                const response = await fetch('/api/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message: userMessage })
                });

                // 创建读取器
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let content = '';

                // 流式读取
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    // 解码并处理数据
                    const chunk = decoder.decode(value);
                    content += chunk;

                    // 更新消息内容（优化渲染性能）
                    requestAnimationFrame(() => {
                        botMessageElement.textContent = content + '▌';
                        scrollToBottom();
                    });
                }

                // 移除光标动画
                botMessageElement.textContent = content;
            } catch (error) {
                console.error('请求失败:', error);
                addMessage('对话服务暂时不可用', 'bot');
            } finally {
                isGenerating = false;
                scrollToBottom();
            }
        }

        // 添加消息到容器
        function addMessage(content, role) {
            const messages = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;
            messageDiv.textContent = content;
            messages.appendChild(messageDiv);
            scrollToBottom();
            return messageDiv;
        }

        // 保持滚动到底部
        function scrollToBottom() {
            const messages = document.getElementById('messages');
            messages.scrollTop = messages.scrollHeight;
        }

        // 回车发送支持
        document.getElementById('input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>